﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using Baggr.FeedParser;
using FeedReader;

namespace Baggr.Agent
{
    public static class Registrator
    {
        public static void Main(string[] args)
        {
            using (var dc = new FeedDataContext())
            {
                while (true)
                {
                    foreach (var feed in dc.Feeds)
                    {
                        Console.WriteLine("Рассматривается фид: {0}", feed.Title);
                        try
                        {
                            var request = WebRequest.Create(feed.Link);
                            Stream stream = request.GetResponse().GetResponseStream();
                            XmlReader reader = XmlReader.Create(stream);
                            foreach (var feedItem in reader.GetFeed().Items)
                            {
                                if(feed.Items.Where(curr => curr.LocalId == feedItem.LocalId).Count() > 0)
                                    continue;
                                var newFeed = new FeedItem()
                                {
                                    Id = Guid.NewGuid(),
                                    Author = feedItem.Author,
                                    Date = feedItem.PublicationDate,
                                    Description = feedItem.Description,
                                    Feed = feed,
                                    Link = feedItem.Link.ToString(),
                                    LocalId = feedItem.LocalId,
                                    Title = feedItem.Title
                                };
                                feed.Items.Add(newFeed);
                                Console.WriteLine("Добавлена запись: {0}", feedItem.Title);
                            }
                        }
                        catch
                        {
                        }
                    }
                    dc.SubmitChanges();
                }
        }

        //if (args.Length > 0 && args[0] == "u")
        //{
        //    Process.Start(
        //        @"c:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe",
        //        "u " + Assembly.GetExecutingAssembly().FullName);
        //}
        //else
        //{
        //    Process.Start(
        //        @"c:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe",
        //        Assembly.GetExecutingAssembly().Location);
        //}
        }
    }
}
